package com.ruoyi.basicsystem.controller;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.basicsystem.service.IZnAccountHeadService;
import com.ruoyi.bill.domain.ZnDepotHead;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.basicsystem.domain.ZnSupplier;
import com.ruoyi.basicsystem.service.IZnSupplierService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 供应商/客户/会员信息Controller
 * 
 * @author nexiaozi
 * @date 2022-02-16
 */
@RestController
@RequestMapping("/basicsystem/supplier")
public class ZnSupplierController extends BaseController
{
    @Autowired
    private IZnSupplierService znSupplierService;

    @Autowired
    private IZnAccountHeadService znAccountHeadService;

    /**
     * 查询供应商/客户/会员信息列表
     */
    @PreAuthorize("@ss.hasAnyPermi('basicsystem:supplier:list,basicsystem:member:list,basicsystem:customer:list')")
    @GetMapping("/list")
    public TableDataInfo list(ZnSupplier znSupplier)
    {
        startPage();
        znSupplier.setDeleteFlag("0");
        List<ZnSupplier> list = znSupplierService.selectZnSupplierList(znSupplier);
        return getDataTable(list);
    }

    /**
     * 导出供应商/客户/会员信息列表
     */
    @PreAuthorize("@ss.hasAnyPermi('basicsystem:supplier:export,basicsystem:member:export,basicsystem:customer:export')")
    @Log(title = "供应商/客户/会员信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ZnSupplier znSupplier)
    {
        znSupplier.setDeleteFlag("0");
        znSupplier.setTenantId(SecurityUtils.getTenantId());
        List<ZnSupplier> list = znSupplierService.selectZnSupplierList(znSupplier);
        ExcelUtil<ZnSupplier> util = new ExcelUtil<ZnSupplier>(ZnSupplier.class);
        util.exportExcel(response, list, znSupplier.getType()+"信息数据");
    }

    /**
     * 获取供应商/客户/会员信息详细信息
     */
    @PreAuthorize("@ss.hasAnyPermi('basicsystem:supplier:query,basicsystem:member:query,basicsystem:customer:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        ZnSupplier znSupplier = znSupplierService.selectZnSupplierById(id);
        if(znSupplier.getType().equals("客户") || znSupplier.getType().equals("供应商")){
            ZnDepotHead znDepotHead = new ZnDepotHead();
            znDepotHead.setOrganId(id);
            znDepotHead.setTenantId(SecurityUtils.getTenantId());
            znDepotHead.setDeleteFlag("0");
            Map<String, BigDecimal> map =znAccountHeadService.selectZnAccountHeadQC(znDepotHead);
            znSupplier.setHaveNeedGet((map !=null && map.containsKey("qcys"))?map.get("qcys").intValue():0);
            znSupplier.setHaveNeedPay((map !=null && map.containsKey("qcyf"))?map.get("qcyf").intValue():0);
        }
        return AjaxResult.success(znSupplier);
    }

    /**
     * 新增供应商/客户/会员信息
     */
    @PreAuthorize("@ss.hasAnyPermi('basicsystem:supplier:add,basicsystem:member:add,basicsystem:customer:add')")
    @Log(title = "供应商/客户/会员信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ZnSupplier znSupplier)
    {
        znSupplier.setTenantId(SecurityUtils.getTenantId());
        znSupplier.setDeleteFlag("0");
        if(znSupplier.getEnabled() ==null){
            znSupplier.setEnabled(0);
        }
        return toAjax(znSupplierService.insertZnSupplier(znSupplier));
    }

    /**
     * 修改供应商/客户/会员信息
     */
    @PreAuthorize("@ss.hasAnyPermi('basicsystem:supplier:edit,basicsystem:member:edit,basicsystem:customer:edit')")
    @Log(title = "供应商/客户/会员信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ZnSupplier znSupplier)
    {
        return toAjax(znSupplierService.updateZnSupplier(znSupplier));
    }

    /**
     * 删除供应商/客户/会员信息
     */
    @PreAuthorize("@ss.hasAnyPermi('basicsystem:supplier:remove,basicsystem:member:remove,basicsystem:customer:remove')")
    @Log(title = "供应商/客户/会员信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(znSupplierService.deleteZnSupplierByIds(ids));
    }

    /**
     * 供应商/客户/会员 状态 启用、停用
     */
    @PreAuthorize("@ss.hasAnyPermi('basicsystem:supplier:status,basicsystem:member:status,basicsystem:customer:status')")
    @Log(title = "供应商/客户/会员信息", businessType = BusinessType.UPDATE)
    @DeleteMapping("/{status}/{ids}")
    public AjaxResult updateStatus(@PathVariable String status,@PathVariable Long[] ids)
    {
        return toAjax(znSupplierService.updateZnSupplierStatusByIds(ids,status));
    }
    /**
     * 导入供应商/客户/会员信息
     * @param file
     * @param type  类型
     * @param updateSupport
     * @return
     * @throws Exception
     */
    @Log(title = "供应商/客户/会员信息导入", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasAnyPermi('basicsystem:supplier:import,basicsystem:member:import,basicsystem:customer:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file,String type, boolean updateSupport) throws Exception
    {
        Date startDate = new Date();
        String startStr = DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss",startDate);
        logger.debug("开始导入数据！");
        ExcelUtil<ZnSupplier> util = new ExcelUtil<ZnSupplier>(ZnSupplier.class);
        List<ZnSupplier> znSupplierList = util.importExcel(file.getInputStream());
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String operName = loginUser.getUsername();
        if (StringUtils.isNull(znSupplierList) || znSupplierList.size() == 0)
        {
            return AjaxResult.error("导入数据不能为空！");
        }
        if(type.equals("0")){
            type = "供应商";
        }else if(type.equals("1")){
            type = "客户";
        }else if(type.equals("2")){
            type = "会员";
        }
        logger.debug("导入数据："+znSupplierList.size());
        String message = znSupplierService.importData(znSupplierList, type , updateSupport, operName);
        logger.debug("结束导入数据！");
        Date endDate = new Date();
        String endStr =  DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss",endDate);
        logger.debug("开始时间："+startStr +",结束时间：" + endStr);
        logger.debug("用时："+(endDate.getTime()-startDate.getTime()));
        logger.debug("用时："+(endDate.getTime()-startDate.getTime())/1000+"s");
        return AjaxResult.success(message);
    }
    /**
     * 模板下载
     * @return
     */
    @PreAuthorize("@ss.hasAnyPermi('basicsystem:supplier:export,basicsystem:member:export,basicsystem:customer:export')")
    @Log(title = "信息模板导出", businessType = BusinessType.EXPORT)
    @PostMapping("/exportTemplate")
    public void exportTemplate(HttpServletResponse response)
    {
        ExcelUtil<ZnSupplier> util = new ExcelUtil<ZnSupplier>(ZnSupplier.class);
        util.exportExcel(response, null, "导入模板");
    }

    /**
     * 查询供应商/客户/会员信息列表
     * 该方法是有受系统配置影响，与上面的表格列表数据查询方法区分开
     */
//    @PreAuthorize("@ss.hasAnyPermi('basicsystem:supplier:list,basicsystem:member:list,basicsystem:customer:list')")
    @GetMapping("/selectlist")
    public AjaxResult selectlist(ZnSupplier znSupplier)
    {
        znSupplier.setTenantId(SecurityUtils.getTenantId());
        znSupplier.setDeleteFlag("0");
        znSupplier.setEnabled(1);
        List<ZnSupplier> list = znSupplierService.selectZnSupplierSelectList(znSupplier);
        return AjaxResult.success(list);
    }
    /**
     * 查询供应商/客户/会员信息列表
     * 该方法是有受系统配置影响，与上面的表格列表数据查询方法区分开
     */
    @PreAuthorize("@ss.hasAnyPermi('system:user:customer')")
    @GetMapping("/listAll")
    public AjaxResult listAll(ZnSupplier znSupplier)
    {
        znSupplier.setTenantId(SecurityUtils.getTenantId());
        znSupplier.setDeleteFlag("0");
        znSupplier.setEnabled(1);
        List<ZnSupplier> list = znSupplierService.selectZnSupplierList(znSupplier);
        return AjaxResult.success(list);
    }
}
